<script setup lang="ts">
import type { CartItem } from '@/types/mall'
import { formatPrice } from '@/utils/mall'

const router = useRouter()
const cartStore = useCartStore()

// 是否编辑模式
const isEditMode = ref(false)

// 购物车数据
const cartItems = computed(() => (cartStore as any).items || [])
const totalQuantity = computed(() => (cartStore as any).totalQuantity || 0)
const selectedQuantity = computed(() => (cartStore as any).selectedQuantity || 0)
const selectedPrice = computed(() => (cartStore as any).selectedPrice || 0)
const isAllSelected = computed(() => (cartStore as any).isAllSelected || false)
const isEmpty = computed(() => (cartStore as any).isEmpty || true)

// 跳转到商品详情
function goToProductDetail(productId: string) {
  uni.navigateTo({ url: `/subPackages/product-package/goodsDetail/index?id=${productId}` })
}

// 跳转到首页
function goToHome() {
  uni.redirectTo({ url: '/pages/index/index' })
}

// 更新商品数量
async function updateQuantity(itemId: string, quantity: number) {
  try {
    await (cartStore as any).updateQuantity(itemId, quantity)
  } catch (error) {
    console.error('更新数量失败:', error)
    uni.showToast({ title: '更新失败', icon: 'none' })
  }
}

// 删除商品
async function removeItem(itemId: string) {
  try {
    uni.showModal({
      title: '确认删除',
      content: '确定要删除这个商品吗？',
      success: async (res) => {
        if (res.confirm) {
          await (cartStore as any).removeItem(itemId)
          uni.showToast({ title: '删除成功', icon: 'success' })
        }
      }
    })
  } catch (error) {
    console.error('删除失败:', error)
    uni.showToast({ title: '删除失败', icon: 'none' })
  }
}

// 切换商品选中状态
function toggleItemSelect(itemId: string) {
  try {
    (cartStore as any).toggleItemSelect(itemId)
  } catch (error) {
    console.error('切换选中状态失败:', error)
  }
}

// 全选/取消全选
function toggleSelectAll() {
  try {
    (cartStore as any).toggleSelectAll()
  } catch (error) {
    console.error('全选操作失败:', error)
  }
}

// 清空购物车
function clearCart() {
  uni.showModal({
    title: '清空购物车',
    content: '确定要清空购物车吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
          await (cartStore as any).clearCart()
          uni.showToast({ title: '购物车已清空', icon: 'success' })
        } catch (error) {
          console.error('清空购物车失败:', error)
          uni.showToast({ title: '操作失败', icon: 'none' })
        }
      }
    }
  })
}

// 删除选中商品
function deleteSelected() {
  if (selectedQuantity.value === 0) {
    uni.showToast({ title: '请先选择商品', icon: 'none' })
    return
  }

  uni.showModal({
    title: '删除选中商品',
    content: `确定要删除选中的${selectedQuantity.value}件商品吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await (cartStore as any).clearSelectedItems()
          uni.showToast({ title: '删除成功', icon: 'success' })
          isEditMode.value = false
        } catch (error) {
          console.error('删除失败:', error)
          uni.showToast({ title: '删除失败', icon: 'none' })
        }
      }
    }
  })
}

// 去结算
function goToCheckout() {
  if (selectedQuantity.value === 0) {
    uni.showToast({ title: '请先选择商品', icon: 'none' })
    return
  }

  // TODO: 跳转到结算页面
  uni.navigateTo({ url: '/pages/checkout/index' })
}

// 切换编辑模式
function toggleEditMode() {
  isEditMode.value = !isEditMode.value
}

// 页面生命周期
onMounted(async () => {
  try {
    await (cartStore as any).initCart()
  } catch (error) {
    console.error('初始化购物车失败:', error)
  }
})
</script>

<template>
  <view class="min-h-screen bg-gray-50 pb-25">
    <!-- 头部 -->
    <view class="flex items-center justify-between p-4 bg-white mb-2.5">
      <view class="flex items-center gap-1">
        <text class="text-lg font-bold text-gray-800">购物车</text>
        <text v-if="totalQuantity > 0" class="text-sm text-gray-500">({{ totalQuantity }})</text>
      </view>
      
      <view v-if="!isEmpty" class="text-primary" @click="toggleEditMode">
        <text class="text-sm">{{ isEditMode ? '完成' : '编辑' }}</text>
      </view>
    </view>

    <!-- 购物车内容 -->
    <view v-if="isEmpty" class="flex flex-col items-center justify-center py-20 px-5">
      <view class="mb-4">
        <wd-icon name="cart" size="80px" color="#ddd" />
      </view>
      <text class="text-lg text-gray-800 mb-2">购物车空空如也</text>
      <text class="text-sm text-gray-500 mb-6">快去添加一些喜欢的商品吧</text>
      <wd-button type="primary" size="large" custom-class="w-40 h-12" @click="goToHome">
        去逛逛
      </wd-button>
    </view>

    <view v-else>
      <!-- 全选 -->
      <view class="flex items-center justify-between px-4 py-3 bg-white mb-2.5">
        <view class="flex items-center gap-2" @click="toggleSelectAll">
          <wd-checkbox :value="isAllSelected" />
          <text class="text-sm text-gray-800">全选</text>
        </view>
        
        <view v-if="isEditMode" class="text-red-500 text-sm" @click="clearCart">
          <text>清空购物车</text>
        </view>
      </view>

      <!-- 商品列表 -->
      <view class="bg-white">
        <view
          v-for="item in cartItems"
          :key="item.id"
          class="flex items-center p-4 border-b border-gray-100 last:border-b-0"
        >
          <!-- 选择框 -->
          <view class="mr-3" @click="toggleItemSelect(item.id)">
            <wd-checkbox :value="item.selected" />
          </view>

          <!-- 商品图片 -->
          <image 
            :src="item.product.images[0]" 
            class="w-20 h-20 rounded-lg mr-3 bg-gray-50" 
            mode="aspectFit"
            @click="goToProductDetail(item.productId)"
          />

          <!-- 商品信息 -->
          <view class="flex-1 mr-3" @click="goToProductDetail(item.productId)">
            <text class="text-sm font-medium text-gray-800 mb-1 line-clamp-2">{{ item.product.name }}</text>
            <text v-if="item.sku" class="text-xs text-gray-500 mb-2">
              规格：{{ Object.values(item.sku.specs || {}).join('，') }}
            </text>
            <view>
              <text class="text-sm font-bold text-red-500">
                {{ formatPrice(item.sku?.price || item.product.defaultPrice) }}
              </text>
            </view>
          </view>

          <!-- 数量控制 -->
          <view>
            <view v-if="!isEditMode">
              <wd-input-number
                :model-value="item.quantity"
                :min="1"
                :max="item.sku?.stock || item.product.stock"
                size="small"
                @change="(event: { value: string | number }) => updateQuantity(item.id, Number(event.value))"
              />
            </view>
            
            <view v-else class="p-2" @click="removeItem(item.id)">
              <wd-icon name="delete" size="20px" color="#ff4142" />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 底部操作栏 -->
    <view v-if="!isEmpty" class="fixed bottom-0 left-0 right-0 bg-white pt-4 pb-4 px-4 border-t border-gray-100" style="padding-bottom: calc(16px + env(safe-area-inset-bottom))">
      <view class="flex items-center justify-between">
        <view class="flex items-center gap-2" @click="toggleSelectAll">
          <wd-checkbox :value="isAllSelected" />
          <text class="text-sm text-gray-800">全选</text>
        </view>
        
        <view class="text-right">
          <text class="text-sm text-gray-600">合计：</text>
          <text class="text-lg font-bold text-red-500">{{ formatPrice(selectedPrice) }}</text>
        </view>
      </view>
      
      <view class="ml-4">
        <wd-button
          v-if="isEditMode"
          type="warning"
          size="large"
          :disabled="selectedQuantity === 0"
          custom-class="min-w-30"
          @click="deleteSelected"
        >
          删除选中({{ selectedQuantity }})
        </wd-button>
        
        <wd-button
          v-else
          type="primary"
          size="large"
          :disabled="selectedQuantity === 0"
          custom-class="min-w-30"
          @click="goToCheckout"
        >
          去结算({{ selectedQuantity }})
        </wd-button>
      </view>
    </view>
  </view>
</template>

<route lang="json">
{
  "name": "cart",
  "layout": "tabbar",
  "style": {
    "navigationBarTitleText": "购物车"
  }
}
</route>